﻿using System;
using System.Collections.Generic;
using System.Linq;
using SuperiorModel;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace Api.SuperiorShop
{
    [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = true)]
    public class ValidateAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            try
            {
                string query = actionContext.Request.RequestUri.Query;
                var parmsDic = GetParmsDic(query);
                string token = parmsDic["Token"] ?? "";
                var isContinue = true;
                if (string.IsNullOrEmpty(token))
                    isContinue = false;
                //--验证token正确性
                //if (!ValidataTool.CheckToken(token))
                //    isContinue = false;
               
                if (!isContinue)
                    actionContext.Response = actionContext.Request.CreateResponse<ApiResultModel<string>>(ApiResultModel<string>.Conclude(ApiResultEnum.Error, "", "非法请求"));
                base.OnActionExecuting(actionContext);
            }
            catch
            {

                actionContext.Response = actionContext.Request.CreateResponse<ApiResultModel<string>>(ApiResultModel<string>.Conclude(ApiResultEnum.Error, "", "非法请求"));
            }


        }
        private IDictionary<string, string> GetParmsDic(string query)
        {
            var parmsStr = query.Split('?')[1];
            IDictionary<string, string> parmsDic = new Dictionary<string, string>();
            parmsStr.Split('&').ToList().ForEach((parm) => {
                parmsDic.Add(parm.Split('=')[0], parm.Split('=')[1]);
            });
            return parmsDic;
        }

    }
}